﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2018/2/21 21:27:01
*说明：<Function>
/**********************************************************************/
using LumenWorks.Framework.IO.Csv;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Utilities
{
    /// <summary>
    /// Csv文件操作类
    /// </summary>
    public class CsvHelper
    {
        /// <summary>
        /// 从csv文件导入到List
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static List<string[]> CsvToLst(string fileName, bool hasHeaders)
        {
            List<string[]> lst = new List<string[]>();
            using (CsvReader csv = new CsvReader(new StreamReader(fileName),
                hasHeaders, CsvReader.DefaultDelimiter, CsvReader.DefaultQuote, CsvReader.DefaultEscape, CsvReader.DefaultComment, ValueTrimmingOptions.None))
            {
                while (csv.ReadNextRecord())
                {
                    string[] aLine = new string[csv.FieldCount];
                    csv.CopyCurrentRecordTo(aLine);
                    lst.Add(aLine);
                }
            }
            return lst;
        }
        /// <summary>
        /// 导出文件为csv
        /// </summary>
        /// <param name="table">数据表</param>
        /// <param name="file">导出路径</param>
        public static void ListToCsv(List<string[]> lst, string file)
        {
            FileStream fs = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), new System.Text.UTF8Encoding(false));
            foreach (string[] item in lst)
            {
                string line = "";
                foreach (string str in item)
                {
                    string tmp = str.Replace("\"", "\"\"");
                    line += "\"" + tmp + "\",";
                }
                line = line.TrimEnd(',');
                sw.WriteLine(line);
            }
            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// 保存报表文件
        /// </summary>
        /// <param name="str"></param>
        /// <param name="file"></param>
        public static void SaveReport(string str, string file)
        {
            FileStream fs = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), Encoding.UTF8);
            sw.Write(str);
            sw.Close();
            fs.Close();
        }

    }
}

